package com.psjj.privilege.web.servlet;

import com.psjj.privilege.po.User;
import com.psjj.privilege.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 个人信息模块
 */
@WebServlet("/personal.do")
public class PersonalController extends BasicServlet {
    private UserService userService = new UserService();
    private static final String BASIC_URL = "/WEB-INF/page/personal/";
    //转发到个人信息查看页面
    private void personalMessage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher(BASIC_URL+"person_message.jsp").forward(req,resp);
    }
    //转发至修改密码页面
    private void updatePasswordUI(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher(BASIC_URL+"update_password.jsp").forward(req,resp);
    }
    //修改个人密码
    private void updatePassword(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获得表单信息
        String oldPwd = req.getParameter("oldPwd");
        String newPwd = req.getParameter("newPwd");
        //获得当前登录的用户名
        HttpSession session = req.getSession();
        User loginUser = (User)session.getAttribute("user");
        String username = loginUser.getUsername();
        //判断老密码输入是否正确
        User user = userService.loginJoinRoles(username, oldPwd);
        if(user!=null){
            //输入正确，修改密码
            userService.updatePassword(username,newPwd);
            session.invalidate();
            //重定向到登录页面
            resp.getWriter().println("<script>parent.location.href='"+req.getContextPath()+"/login.jsp';</script>");
        }else {
            //输入错误
            req.setAttribute("error","原密码输入有误");
            req.getRequestDispatcher(BASIC_URL+"update_password.jsp").forward(req,resp);
        }
    }
}
